package order

import (
	"errors"
	"go-ddd-ecommerce/internal/domain/events"
	"time"

	"github.com/google/uuid"
)

// Order 订单实体 - 充血模型
type Order struct {
	ID          uuid.UUID
	UserID      uuid.UUID
	ProductID   uuid.UUID
	Quantity    int
	TotalAmount float64
	Status      string
	CreatedAt   time.Time
	events      []events.DomainEvent // 记录领域事件,临时存储待发布的事件
}

// NewOrder 创建订单
func NewOrder(userID, productID uuid.UUID, quantity int, unitPrice float64) (*Order, error) {
	if quantity <= 0 {
		return nil, errors.New("购买数量必须大于0")
	}
	if unitPrice <= 0 {
		return nil, errors.New("单价必须大于0")
	}
	totalAmount := unitPrice * float64(quantity)

	order := &Order{
		ID:          uuid.New(),
		UserID:      userID,
		ProductID:   productID,
		Quantity:    quantity,
		TotalAmount: totalAmount,
		Status:      "completed",
		CreatedAt:   time.Now(),
		events:      make([]events.DomainEvent, 0),
	}
	// 发布订单创建事件
	order.events = append(order.events, events.NewOrderCreatedEvent(
		order.ID, userID, productID, quantity, totalAmount,
	))
	return order, nil
}

// GetDomainEvents 获取待发布的事件
// 实现事件生产器的接口
func (o *Order) GetDomainEvents() []events.DomainEvent {
	return o.events
}

// ClearDomainEvents 清空已发布的事件
// 实现事件生产器的接口
func (o *Order) ClearDomainEvents() {
	o.events = make([]events.DomainEvent, 0)
}

// Cancel 取消订单
//func (o *Order) Cancel() error {
//	if o.Status == "cancelled" {
//		return errors.New("订单已取消")
//	}
//	o.Status = "cancelled"
//	return nil
//}
